<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/5/5
 * Time: 16:24
 */

namespace app\logic\index\weixin;



use app\common\lib\Wechat;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\logic\index\user\UserLogic;
use app\model\user\UserModel;

class WeixinLogic extends BaseLogic
{
    protected $weixinUserModel;

    protected $weixinOpenRequestModel;

    protected static $instance;

    public function __construct()
    {
        parent::__construct();
        $this->weixinUserModel = \app\model\weixin\WeixinUserinfo::getInstance();
        $this->weixinOpenRequestModel = \app\model\weixin\WeixinOpenRequestLog::getInstance();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function getWeixinLogin($param)
    {
        $accessTokenRes = Wechat::getInstance()->getAccessTokenByCode($param['code']);

        if(empty($accessTokenRes['unionid'])){
            throw new IndexException(4020,'获取access_token失败,请稍后再试');
        }

        $info = $this->weixinUserModel->where(['unionid'=>$accessTokenRes['unionid']])->first();

        if($info==false){
            $userInfoRes = Wechat::getInstance()->getUserInfoByOpenID($accessTokenRes['access_token'],$accessTokenRes['openid']);
            if(empty($userInfoRes['nickname'])){
                throw new IndexException(4020,'获取用户信息失败,请稍后再试');
            }
            $id = $this->weixinUserModel->insertData($userInfoRes);
            $info = $this->weixinUserModel->find($id);
        }

        //判断是否已经添加到用户表
        $user = UserModel::getInstance()->where(['weixin_unionid'=>$accessTokenRes['unionid'],'isdel'=>0])->first();
        if($user==false){
            $userParam = [];
            $info['nickname'] && $userParam['nickname'] = $info['nickname'];
            $info['headimgurl'] && $userParam['headimgurl'] = $info['headimgurl'];
            $info['unionid'] && $userParam['weixin_unionid'] = $info['unionid'];
            $user = UserLogic::getInstance()->createUser($userParam);

            $info->userid = $user['user_sn'];
            $info->save();
        }

        $user = UserLogic::getInstance()->getInfo($user);

        $user = $this->loginData($user);

        return $user;
    }

    /**
     * 微信绑定
     * @param $param
     * @return false|mixed
     * @throws IndexException
     */
    public function bind($param)
    {
        //分布式锁
        $lock = Common::setnx('wechat_bind_lock:user_id:' . request()->curUserId);
        if (!$lock) {
            throw new IndexException(10,  '请求过快,请休息一下');
        }

        //用户表信息
        $userInfo = UserModel::getInstance()->where(['user_sn' => request()->curUserId])->first();
        if (empty($userInfo)) {
            throw new IndexException(2008,'用户信息缺失');
        }

        //获取微信openid
        $accessTokenRes = Wechat::getInstance()->getAccessTokenByCode($param['code']);
        if (empty($accessTokenRes['openid'])) {
            throw new IndexException(2008,'获取access_token失败,请稍后再试');
        }

        //获取微信用户信息
        $userInfoRes = Wechat::getInstance()->getUserInfoByOpenID($accessTokenRes['access_token'], $accessTokenRes['openid']);
        if (empty($userInfoRes['nickname'])) {
            throw new IndexException(2008,'获取用户信息失败,请稍后再试');
        }

        //获取微信用户信息
        $userWechatInfo = WeixinUserinfo::getInstance()->where(['userid' => $userInfo->userid])->first();
        if (!empty($userWechatInfo)) {
            throw new IndexException(2008,'用户已经绑定微信,请勿重复操作');
        }

        try {
            //进行微信绑定
            if (!empty($userInfoRes['headimgurl'])) {
                $res = Upload::getInstance()->stringUploadFile($userInfoRes['headimgurl'],'weixin');
            }
            $insert = [
                'userid'     => $userInfo->userid,
                'openid'     => $accessTokenRes['openid'] ?? '',
                'nickname'   => $userInfoRes['nickname'] ?? '',
                'sex'        => $userInfoRes['sex'] ?? '',
                'province'   => $userInfoRes['province'] ?? '',
                'city'       => $userInfoRes['city'] ?? '',
                'country'    => $userInfoRes['country'] ?? '',
                'headimgurl' => $userInfoRes['headimgurl'] && isset($res['request-url']) ? $res['request-url'] : '',
                'privilege'  => $userInfoRes['privilege'] ? json_encode($userInfoRes['privilege'],256) : '',
                'createtime' => date('Y-m-d H:i:s'),
            ];
            WeixinUserinfo::getInstance()->insert($insert);
        } catch (IndexException $e) {
            throw new IndexException(500,'微信绑定失败');
       }

        return [
            'nickname'   => $userInfoRes['nickname'] ?? '',
            'headimgurl' => $userInfoRes['headimgurl'] ?? '',
            'sex'        => $userInfoRes['sex'] ?? 0, //普通用户性别，1 为男性，2 为女性
            'city'       => $userInfoRes['city'] ?? '',
            'country'    => $userInfoRes['country'] ?? '',
        ];
    }

    public function getWechatOpenId($param)
    {
        $accessTokenRes = Wechat::getInstance()->getOpenIdByCode($param['code']);

        if(empty($accessTokenRes['openid'])){
            throw new IndexException(2008,'请稍后再试');
        }

        $info = $this->weixinUserModel->where(['openid'=>$accessTokenRes['openid']])->first();

        if($info==false){
            $id = $this->weixinUserModel->insertData($accessTokenRes);
        }else{
            $info->session_key = $accessTokenRes['session_key'];
            $info->save();
        }

        return $accessTokenRes;
    }


}
